package com.autotest.nore.service;

import com.alibaba.fastjson2.JSONObject;
import com.autotest.nore.common.constants.AssertionMethod;
import com.autotest.nore.common.utils.*;
import com.autotest.nore.domain.*;
import com.autotest.nore.dto.*;
import com.autotest.nore.mapper.*;
import com.autotest.nore.request.RunRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.JsonPath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;

import javax.mail.MessagingException;


@Service
public class RunService {
    private static final Logger logger = LoggerFactory.getLogger(RunService.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private CollectionCaseMapper collectionCaseMapper;
    @Autowired
    private CaseApiMapper caseApiMapper;
    @Autowired
    private ApiMapper apiMapper;
    @Autowired
    private DomainMapper domainMapper;
    @Autowired
    private ReportCollectionMapper reportCollectionMapper;
    @Autowired
    private ReportCollectionCaseMapper reportCollectionCaseMapper;
    @Autowired
    private ReportCollectionCaseApiMapper reportCollectionCaseApiMapper;
    @Autowired
    private EnvironmentMapper environmentMapper;
    @Autowired
    private CaseMapper caseMapper;
    @Autowired
    private EnvironmentParamMapper environmentParamMapper;
    @Autowired
    private ReportStatisticsMapper reportStatisticsMapper;
    @Autowired
    private ReportStatusMapper reportStatusMapper;
    @Autowired
    private DatabaseMapper databaseMapper;
    @Autowired
    private PlanCollectionMapper planCollectionMapper;
    @Autowired
    private CollectionMapper collectionMapper;



    /**
     * 构建带有查询参数的URL
     *
     * @param baseUrl     基础URL
     * @param queryParams 查询参数列表
     * @return 最终的URL
     */
    public static String buildUrlWithParams(String baseUrl, JSONArray queryParams) {
        StringBuilder urlBuilder = new StringBuilder(baseUrl);

        // 检查是否需要添加问号
        if (baseUrl.indexOf('?') == -1) {
            urlBuilder.append('?');
        } else {
            urlBuilder.append('&');
        }

        // 添加查询参数
        for (int i = 0; i < queryParams.size(); i++) {
            JSONObject param = queryParams.getJSONObject(i);
            String name = param.getString("name");
            String value = param.getString("value");

            if (i > 0) {
                urlBuilder.append('&');
            }
            urlBuilder.append(name).append('=').append(value);
        }

        return urlBuilder.toString();
    }


    /**
     * 断言响应
     *
     * @param assertions 断言配置
     * @param response   响应体
     * @param statusCode 状态码
     * @return 断言结果
     */
    private boolean assertResponse(JsonNode assertions, String response,
                                   int statusCode, Map<String, String> responseHeaders,
                                   StringBuilder execLog, Map<String, String> variables) {
        Iterator<JsonNode> elements = assertions.elements();
        while (elements.hasNext()) {
            JsonNode assertion = elements.next();
            String expect = assertion.get("expect").asText();
            String expression = assertion.get("expression").asText();
            String method = assertion.get("method").asText();
            String from = assertion.get("from").asText();
            String assertionType = assertion.get("assertion").asText();
            String actualValue;
            // 解析期望值中的变量
            expect = processVariableUtils.processStr(expect, variables);

            switch (from) {
                case "resBody":
                    actualValue = AssertionUtils.extractValue(from, expression, method, response).toString();
                    break;
                case "resHeader":
                    actualValue = AssertionUtils.extractValue(from, expression, method, JSON.toJSONString(responseHeaders)).toString();
                    break;
                case "resCode":
                    actualValue = Integer.toString(statusCode);
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported from value: " + from);
            }

            boolean assertionResult = AssertionUtils.assertValue(actualValue, expect, AssertionMethod.valueOf(assertionType));
            if (!assertionResult) {
                execLog.append(formatLog("Error", "接口断言失败: (" + assertionType + ")实际值(" + actualValue + ")预期值(" + expect + ")"));
                return false;
            }
        }
        return true;
    }

    private String formatLog(String level, String message) {
        return String.format("%s - %s - %s<br><br>", getCurrentTimestamp(), level, message);
    }

    private String getCurrentTimestamp() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
    }

    /**
     * 初始化环境变量
     *
     * @param runRequest 运行请求对象，包含环境ID和项目ID等信息
     * @return 包含环境变量的Map集合
     */
    private Map<String, String> initializeEnvironmentVariables(RunRequest runRequest) {
        Map<String, String> variables = new HashMap<>();
        // 获取环境ID和环境名称
        String environmentId = runRequest.getEnvironmentId();
        String environmentName = environmentMapper.getNameById(environmentId);
        String projectId = runRequest.getProjectId();
        // 确保 environmentId 被放入 variables 中
        variables.put("environmentId", environmentId);
        variables.put("environmentName", environmentName);
        variables.put("projectId", projectId);
        // 查询环境参数并存储到全局变量中
        Map<String, String> proEnv = new HashMap<>();
        proEnv.put("environmentName", environmentName);
        proEnv.put("projectId", projectId);

        List<EnvironmentParamDTO> paramDatas = environmentParamMapper.getParamByEnv(proEnv);
        for (EnvironmentParamDTO paramData : paramDatas) {
            variables.put(paramData.getName(), paramData.getParamData());
        }
        // 查询公共参数并存储到全局变量中
        List<EnvironmentParamDTO> paramDatas2 = environmentParamMapper.getParamByCom();
        for (EnvironmentParamDTO paramData2 : paramDatas2) {
            variables.put(paramData2.getName(), paramData2.getParamData());
        }

        return variables;
    }

    /**
     * 初始化测试报告
     *
     * @param runRequest 运行请求对象
     * @param reportId   报告ID
     * @return 初始化的报告对象
     */
    private Report initializeReport(RunRequest runRequest, String reportId) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
        // 创建报告对象并设置属性
        Report reportDTO = new Report();
        reportDTO.setId(reportId);
        reportDTO.setName(runRequest.getSourceName() + formattedDateTime);
        reportDTO.setEnvironmentId(runRequest.getEnvironmentId());
        reportDTO.setSourceType(runRequest.getSourceType());
        reportDTO.setSourceId(runRequest.getSourceId());
        reportDTO.setStatus("start");
        reportDTO.setProjectId(runRequest.getProjectId());
        reportDTO.setCreateTime(System.currentTimeMillis());
        reportDTO.setUpdateTime(System.currentTimeMillis());
        reportDTO.setCreateUser(runRequest.getRunUser());
        reportDTO.setUpdateUser(runRequest.getRunUser());
        // 插入报告记录到数据库
        reportMapper.addReport(reportDTO);
        return reportDTO;
    }

    /**
     * 初始化集合报告
     *
     * @param reportId       报告ID
     * @param collectionId   集合ID
     * @param collectionName 集合名称
     * @param caseTotal      用例总数
     * @return 集合报告ID
     */
    private String initializeReportCollection(String reportId, String collectionId, String collectionName, int caseTotal) {
        ReportCollection reportCollectionDTO = new ReportCollection();
        String reportCollectionId = UUID.randomUUID().toString();
        // 设置集合报告属性
        reportCollectionDTO.setId(reportCollectionId);
        reportCollectionDTO.setReportId(reportId);
        reportCollectionDTO.setCollectionId(collectionId);
        reportCollectionDTO.setCollectionName(collectionName);
        reportCollectionDTO.setCaseTotal(caseTotal);
        // 插入集合报告记录到数据库
        reportCollectionMapper.addReportCollection(reportCollectionDTO);
        return reportCollectionId;
    }

    /**
     * 执行单个用例
     *
     * @param caseId             用例ID
     * @param collectionId       集合ID
     * @param reportCollectionId 集合报告ID
     * @param variables          全局变量集合
     */
    private void executeCase(String caseId, String collectionId, String reportCollectionId, Map<String, String> variables) {
        // 1. 获取用例在集合中的索引和名称
        // 查询数据库，获取当前用例在集合中的索引和用例名称
        int collectionCaseIndex=0;
        if(collectionId.equals("debug-collection")){
            collectionCaseIndex=0;
        }else{
            Map<String, String> caseCollectionParams = new HashMap<>();
            caseCollectionParams.put("caseId", caseId);
            caseCollectionParams.put("collectionId", collectionId);
            collectionCaseIndex = collectionCaseMapper.getIndex(caseCollectionParams);
        }
        String caseName = caseMapper.getCaseName(caseId);
        // 2. 创建用例级别的变量副本
        Map<String, String> caseVariables = new HashMap<>(variables);

        // 3. 加载用例自定义变量
        String caseVariableJson = caseMapper.getCaseVariables(caseId);
        if (caseVariableJson != null && !caseVariableJson.isEmpty()) {
            try {
                JsonNode variableNode = objectMapper.readTree(caseVariableJson);
                Iterator<Map.Entry<String, JsonNode>> fields = variableNode.fields();
                while (fields.hasNext()) {
                    Map.Entry<String, JsonNode> entry = fields.next();
                    caseVariables.put(entry.getKey(), entry.getValue().asText());
                }
            } catch (Exception e) {
                logger.error("解析用例变量失败: " + e.getMessage());
            }
        }
        // 4. 记录用例开始时间
        long caseStartTime = System.currentTimeMillis();
        // 5. 生成唯一的用例报告ID
        String reportCollectionCaseId = UUID.randomUUID().toString();
        // 6. 获取用例中的API列表
        // 查询数据库，获取当前用例中包含的所有API列表
        List<ApiCaseDTO> apiCaseDTOList = caseApiMapper.getCaseApiIndex(caseId);
        boolean caseStatus = true; // 用例执行状态，默认为成功
        // 7. 遍历用例中的API并执行
        for (ApiCaseDTO apiCaseDTO : apiCaseDTOList) {
            // 执行单个API用例，并更新用例状态
            boolean apiStatus = executeApiCase(apiCaseDTO, reportCollectionCaseId, caseVariables);
            if (!apiStatus) {
                caseStatus = false; // 如果任意一个API执行失败，则用例状态为失败
            }
        }
        // 8. 记录用例结束时间
        long caseEndTime = System.currentTimeMillis();
        long caseDuringTime = caseEndTime - caseStartTime;
        // 9. 插入用例报告记录
        // 将用例的执行结果插入到 `report_collection_case` 表中
        ReportCollectionCase reportCollectionCase = new ReportCollectionCase();
        reportCollectionCase.setId(reportCollectionCaseId);
        reportCollectionCase.setReportCollectionId(reportCollectionId);// 关联集合报告ID
        reportCollectionCase.setCollectionCaseIndex(collectionCaseIndex);// 用例在集合中的索引
        reportCollectionCase.setCaseId(caseId);// 用例ID
        reportCollectionCase.setCaseType("API");// 用例类型（固定为API）
        reportCollectionCase.setCaseName(caseName);// 用例名称
        reportCollectionCase.setRunTimes(1);// 执行次数（默认为1）
        reportCollectionCase.setStartTime(caseStartTime);// 用例开始时间
        reportCollectionCase.setEndTime(caseEndTime);// 用例结束时间
        reportCollectionCase.setDuring(String.valueOf(caseDuringTime));// 用例执行耗时
        reportCollectionCase.setStatus(String.valueOf(caseStatus));// 用例执行状态
        reportCollectionCaseMapper.addReportCollectionCase(reportCollectionCase);
        // 10. 更新集合报告的状态
        if (!caseStatus) {
            reportCollectionMapper.updateStatus(reportCollectionId, "false");
        } else {
            reportCollectionMapper.updateStatus(reportCollectionId, "true");
        }
    }

    /**
     * 执行单个API用例
     *
     * @param apiCaseDTO             API用例对象
     * @param reportCollectionCaseId 用例报告ID
     * @param variables              全局变量集合
     * @return API用例执行结果（true：成功，false：失败）
     */
    private boolean executeApiCase(ApiCaseDTO apiCaseDTO, String reportCollectionCaseId, Map<String, String> variables) {
        boolean responseStatus = true;
        StringBuilder execLog = new StringBuilder();
        try{
            // 初始化 Context
            GraalVMScriptUtils.initializeContext();
            //解析前置脚本和后置脚本
            JsonNode controllerNode = parseController(apiCaseDTO.getCaseapiController());
            String preScript = extractScript(controllerNode, "preScript");
            String postScript = extractScript(controllerNode, "postScript");
            // 执行前置脚本
            if (!executePreScript(preScript, variables, execLog)) {
                responseStatus = false; // 如果前置脚本执行失败，返回 false
            }
            // 解析前置SQL和后置SQL
            String preSql = extractScript(controllerNode, "preSql");
            String postSql = extractScript(controllerNode, "postSql");
            // 执行前置SQL
            if (preSql != null && !preSql.isEmpty()) {
                if (!executeSqlScript(variables.get("environmentId"), preSql, variables, execLog)) {
                    responseStatus = false; // 如果前置SQL执行失败，返回 false
                }
            }
            // 解析前置等待和后置等待
            String preSleep=extractScript(controllerNode, "sleepBeforeRun");
            String postSleep=extractScript(controllerNode, "sleepAfterRun");
            if(preSleep!=null){
                //执行前置等待
                try {
                    Thread.sleep(Integer.parseInt(preSleep));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            // 获取请求环境地址
            String domainKey = apiCaseDTO.getDomainSign();
            Domain domainDTO = domainMapper.getDomainByName(variables.get("environmentId"), domainKey);
            String domainData = domainDTO.getDomainData();
            // 处理请求参数
            String method = apiCaseDTO.getMethod();
            String path = apiCaseDTO.getPath();
            JsonNode headerNode = parseJson(apiCaseDTO.getCaseapiHeader());
            JsonNode bodyNode = parseJson(apiCaseDTO.getCaseapiBody());
            JsonNode queryNode = parseJson(apiCaseDTO.getCaseapiQuery());

            String processedHeader = processJsonNode(headerNode, variables);
            String processedBody = processJsonNode(bodyNode, variables);
            String processedQuery = processJsonNode(queryNode, variables);
            String path2 = processVariableUtils.processStr(path, variables);
            // 构建最终 URL
            JSONArray queryParams = JSON.parseArray(processedQuery);
            String baseUrl = domainData + path2;
            String finalUrl = buildUrlWithParams(baseUrl, queryParams);
            // 组装请求头
            HashMap<String, String> requestHeaders = new HashMap<>();
            HeaderParserUtils.parseHeaders(processedHeader, requestHeaders);
            // 处理请求体
            Map<String, Object> requestBody = new HashMap<>();
            if (processedBody != null && !processedBody.equals("null") && !processedBody.equals("{}")) {
                requestBody = BodyParserUtils.parseBody(processedBody);
            }
            // 执行 HTTP 请求
            String response;
            Map<String, String> responseHeaders;
            int statusCode = 0;

            long apiStartTime = System.currentTimeMillis();
            //获取代理
            String rest=apiCaseDTO.getRest();
            //判断代理是否为空
            if(rest==null || rest.trim().isEmpty() ||rest.trim().equals("[]")){
                try {
                    response = executeHttpRequest(method, finalUrl, requestHeaders, requestBody);
                    responseHeaders = HttpclientUtils.getResponseHeaders();
                    // 根据响应字符串设置状态码
                    if (response.startsWith("请求失败:")) {
                        statusCode = Integer.parseInt(response.split(":::", 3)[1]);
                    } else if (response.startsWith("请求异常:")) {
                        statusCode = 500;
                    } else {
                        statusCode = 200;
                    }
                } catch (Exception e) {
                    response = "请求异常%s".formatted(e.getMessage());
                    responseHeaders = null;
                    execLog.append(formatLog("Error", "请求异常: " + e.getMessage()));
                    statusCode = 500;
                }
            }else{
                String proxyHost=rest.split(":")[0];
                int proxyPort=Integer.parseInt(rest.split(":")[1]);
                try {
                    response = executeHttpRequestWithProxy(method, finalUrl, requestHeaders, requestBody, proxyHost, proxyPort);
                    responseHeaders = HttpclientUtils.getResponseHeaders();
                    // 根据响应字符串设置状态码
                    if (response.startsWith("请求失败:")) {
                        statusCode = Integer.parseInt(response.split(":::", 3)[1]);
                    } else if (response.startsWith("请求异常:")) {
                        statusCode = 500;
                    } else {
                        statusCode = 200;
                    }
                } catch (Exception e) {
                    response = "请求异常%s".formatted(e.getMessage());
                    responseHeaders = null;
                    execLog.append(formatLog("Error", "请求异常: " + e.getMessage()));
                    statusCode = 500;
                }
            }


            long apiEndTime = System.currentTimeMillis();
            long apiDuring = apiEndTime - apiStartTime;
            // 如果请求失败，保存结果并返回
            if (statusCode != 200) {
                saveApiCaseResult(apiCaseDTO, reportCollectionCaseId, execLog, apiDuring, false, finalUrl, String.valueOf(requestHeaders), String.valueOf(requestBody), responseHeaders, response, statusCode);
                return false;
            }
            if(postSleep!=null){
                //执行后置等待
                try {
                    Thread.sleep(Integer.parseInt(postSleep));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            // 执行后置SQL
            if (postSql != null && !postSql.isEmpty()) {
                if (!executeSqlScript(variables.get("environmentId"), postSql, variables, execLog)) {
                    responseStatus = false; // 如果后置SQL执行失败，返回 false
                }
            }
            // 执行后置处理
            if (!executePostProcessing(apiCaseDTO.getCaseapiRelation(), response, responseHeaders, variables, execLog)) {
                responseStatus = false; // 如果后置处理失败，返回 false
            }
            // 执行后置脚本
            if (!executePostScript(postScript, variables, execLog)) {
                responseStatus = false; // 如果后置脚本执行失败，返回 false
            }
            // 执行断言
            boolean assertionResult = executeAssertions(apiCaseDTO.getCaseapiAssertion(), response, statusCode, responseHeaders, execLog, variables);

            // 保存 API 用例结果
            saveApiCaseResult(apiCaseDTO, reportCollectionCaseId, execLog, apiDuring, assertionResult && responseStatus, finalUrl, String.valueOf(requestHeaders), String.valueOf(requestBody), responseHeaders, response, statusCode);

            return assertionResult && responseStatus;

        }finally {
            // 关闭 Context
            GraalVMScriptUtils.closeContext();
        }

    }

    /**
     * 执行HTTP请求
     *
     * @param method         请求方法（GET/POST/PUT等）
     * @param finalUrl       请求URL
     * @param requestHeaders 请求头
     * @param requestBody    请求体
     * @return 响应内容
     * @throws Exception 请求异常
     */
    private String executeHttpRequest(String method, String finalUrl, Map<String, String> requestHeaders, Map<String, Object> requestBody) throws Exception {
        switch (method.toUpperCase()) {
            case "GET":
                return HttpclientUtils.httpCommonGet(finalUrl, requestHeaders);
            case "POST":
                if ("application/json".equals(requestBody.get("contentType"))) {
                    return HttpclientUtils.httpJsonPost(finalUrl, requestHeaders, JSONObject.parseObject(requestBody.get("body").toString()));
                } else if ("multipart/form-data".equals(requestBody.get("contentType"))) {
                    return HttpclientUtils.httpMultipartPost(finalUrl, requestHeaders, (Map<String, Object>) requestBody.get("body"));
                } else if ("text".equals(requestBody.get("contentType"))) {
                    return HttpclientUtils.httpRawPost(finalUrl, requestHeaders, requestBody.get("body").toString());
                } else if ("html".equals(requestBody.get("contentType"))) {
                    return HttpclientUtils.httpHtmlPost(finalUrl, requestHeaders, requestBody.get("body").toString());
                } else if ("xml".equals(requestBody.get("contentType"))) {
                    return HttpclientUtils.httpXmlPost(finalUrl, requestHeaders, requestBody.get("body").toString());
                } else if ("application/x-www-form-urlencoded".equals(requestBody.get("contentType"))) {
                    return HttpclientUtils.httpCommonPost(finalUrl, requestHeaders, (Map<String, Object>) requestBody.get("body"));
                } else if ("none".equals(requestBody.get("contentType"))) {
                    return HttpclientUtils.httpCommonPost(finalUrl, requestHeaders, null);
                } else {
                    throw new UnsupportedOperationException("不支持的请求体类型: " + requestBody.get("contentType"));
                }
            case "PUT":
                if ("application/json".equals(requestBody.get("contentType"))) {
                    return HttpclientUtils.httpJsonPut(finalUrl, requestHeaders, JSONObject.parseObject(requestBody.get("body").toString()));
                } else {
                    throw new UnsupportedOperationException("不支持的请求体类型: " + requestBody.get("contentType"));
                }
            case "DELETE":
                return HttpclientUtils.httpDelete(finalUrl, requestHeaders);
            case "HEAD":
                return HttpclientUtils.httpHead(finalUrl, requestHeaders);
            case "PATCH":
                if ("application/json".equals(requestBody.get("contentType"))) {
                    return HttpclientUtils.httpPatch(finalUrl, requestHeaders, JSONObject.parseObject(requestBody.get("body").toString()));
                } else {
                    throw new UnsupportedOperationException("不支持的请求体类型: " + requestBody.get("contentType"));
                }
            case "OPTIONS":
                return HttpclientUtils.httpOptions(finalUrl, requestHeaders);
            default:
                throw new IllegalArgumentException("Unsupported HTTP method: " + method);
        }
    }

    /**
     * 执行带代理的 HTTP 请求
     *
     * @param method         请求方法（GET/POST/PUT等）
     * @param finalUrl       请求URL
     * @param requestHeaders 请求头
     * @param requestBody    请求体
     * @param proxyHost      代理主机
     * @param proxyPort      代理端口
     * @return 响应内容
     * @throws Exception 请求异常
     */
    private String executeHttpRequestWithProxy(String method, String finalUrl, Map<String, String> requestHeaders,
                                               Map<String, Object> requestBody, String proxyHost, int proxyPort) throws Exception {
        switch (method.toUpperCase()) {
            case "GET":
                return HttpclientUtils.httpCommonGetWithProxy(finalUrl, requestHeaders, proxyHost, proxyPort);
            case "POST":
                if ("application/json".equals(requestBody.get("contentType"))) {
                    return HttpclientUtils.httpJsonPostWithProxy(finalUrl, requestHeaders,
                            JSONObject.parseObject(requestBody.get("body").toString()), proxyHost, proxyPort);
                } else if ("multipart/form-data".equals(requestBody.get("contentType"))) {
                    return HttpclientUtils.httpMultipartPostWithProxy(finalUrl, requestHeaders,
                            (Map<String, Object>) requestBody.get("body"), proxyHost, proxyPort);
                } else if ("text".equals(requestBody.get("contentType"))) {
                    return HttpclientUtils.httpRawPostWithProxy(finalUrl, requestHeaders,
                            requestBody.get("body").toString(), proxyHost, proxyPort);
                } else if ("html".equals(requestBody.get("contentType"))) {
                    return HttpclientUtils.httpHtmlPostWithProxy(finalUrl, requestHeaders,
                            requestBody.get("body").toString(), proxyHost, proxyPort);
                } else if ("xml".equals(requestBody.get("contentType"))) {
                    return HttpclientUtils.httpXmlPostWithProxy(finalUrl, requestHeaders,
                            requestBody.get("body").toString(), proxyHost, proxyPort);
                } else if ("application/x-www-form-urlencoded".equals(requestBody.get("contentType"))) {
                    return HttpclientUtils.httpCommonPostWithProxy(finalUrl, requestHeaders,
                            (Map<String, Object>) requestBody.get("body"), proxyHost, proxyPort);
                } else if ("none".equals(requestBody.get("contentType"))) {
                    return HttpclientUtils.httpCommonPostWithProxy(finalUrl, requestHeaders, null, proxyHost, proxyPort);
                } else {
                    throw new UnsupportedOperationException("不支持的请求体类型: " + requestBody.get("contentType"));
                }
            case "PUT":
                if ("application/json".equals(requestBody.get("contentType"))) {
                    return HttpclientUtils.httpJsonPutWithProxy(finalUrl, requestHeaders,
                            JSONObject.parseObject(requestBody.get("body").toString()), proxyHost, proxyPort);
                } else {
                    throw new UnsupportedOperationException("不支持的请求体类型: " + requestBody.get("contentType"));
                }
            case "DELETE":
                return HttpclientUtils.httpDeleteWithProxy(finalUrl, requestHeaders, proxyHost, proxyPort);
            case "HEAD":
                return HttpclientUtils.httpHeadWithProxy(finalUrl, requestHeaders, proxyHost, proxyPort);
            case "PATCH":
                if ("application/json".equals(requestBody.get("contentType"))) {
                    return HttpclientUtils.httpPatchWithProxy(finalUrl, requestHeaders,
                            JSONObject.parseObject(requestBody.get("body").toString()), proxyHost, proxyPort);
                } else {
                    throw new UnsupportedOperationException("不支持的请求体类型: " + requestBody.get("contentType"));
                }
            case "OPTIONS":
                return HttpclientUtils.httpOptionsWithProxy(finalUrl, requestHeaders, proxyHost, proxyPort);
            default:
                throw new IllegalArgumentException("Unsupported HTTP method: " + method);
        }
    }

    //后置处理逻辑
    private boolean executePostProcessing(String caseapiRelation, String response, Map<String, String> responseHeaders, Map<String, String> variables, StringBuilder execLog) {
        if (caseapiRelation != null && !caseapiRelation.isEmpty()) {
            try {
                JsonNode relationNode = objectMapper.readTree(caseapiRelation);
                Iterator<JsonNode> elements = relationNode.elements();
                while (elements.hasNext()) {
                    JsonNode relation = elements.next();
                    String expression = relation.get("expression").asText();
                    String methodRelation = relation.get("method").asText();
                    String name = relation.get("name").asText();
                    String from = relation.get("from").asText();

                    try {
                        if ("resBody".equals(from)) {
                            if ("jsonpath".equalsIgnoreCase(methodRelation)) {
                                Object valueTemp = JsonPath.parse(response).read(expression);
                                if (valueTemp != null) {
                                    variables.put(name, String.valueOf(valueTemp));
                                    execLog.append(formatLog("Debug", "后置结果处理: 关联变量名" + name+",提取值"+String.valueOf(valueTemp)));
                                }
                            } else if ("regular".equalsIgnoreCase(methodRelation)) {
                                Pattern pattern = Pattern.compile(expression);
                                Matcher matcher = pattern.matcher(response);
                                if (matcher.find()) {
                                    variables.put(name, matcher.group());
                                    execLog.append(formatLog("Debug", "后置结果处理: 关联变量名" + name+",提取值"+matcher.group()));
                                }
                            }
                        } else if ("resHeader".equals(from)) {
                            if ("jsonpath".equalsIgnoreCase(methodRelation)) {
                                String value = JsonPath.read(response, expression);
                                if (value != null) {
                                    variables.put(name, value);
                                    execLog.append(formatLog("Debug", "后置结果处理: 关联变量名" + name+",提取值"+String.valueOf(value)));
                                }
                            } else if ("regular".equalsIgnoreCase(methodRelation)) {
                                String headerValue = responseHeaders.get(expression);
                                if (headerValue != null) {
                                    Pattern pattern = Pattern.compile(expression);
                                    Matcher matcher = pattern.matcher(headerValue);
                                    if (matcher.find()) {
                                        variables.put(name, matcher.group());
                                        execLog.append(formatLog("Debug", "后置结果处理: 关联变量名" + name+",提取值"+matcher.group()));
                                    }
                                }
                            }
                        }

                    } catch (com.jayway.jsonpath.PathNotFoundException e) {
                        // 捕获 JsonPath 路径未找到异常
                        execLog.append(formatLog("Warn", "后置处理未找到路径: " + expression + ", 异常: " + e.getMessage()));
                        logger.warn("后置处理未找到路径: " + expression, e);
                        return false; // 执行失败
                    } catch (Exception e) {
                        // 捕获其他异常
                        execLog.append(formatLog("Error", "后置处理异常: " + e.getMessage()));
                        logger.error("后置处理异常: " + e.getMessage(), e);
                        return false; // 执行失败
                    }
                }
                return true; // 执行成功
            } catch (Exception e) {
                execLog.append(formatLog("Error", "后置处理异常: " + e.getMessage()));
                return false; // 执行失败
            }
        }
        return true; // 如果没有后置处理逻辑，直接返回成功
    }

    //断言执行逻辑
    private boolean executeAssertions(String caseapiAssertion, String response,
                                      int statusCode, Map<String, String> responseHeaders,
                                      StringBuilder execLog, Map<String, String> variables) {
        if (caseapiAssertion != null && !caseapiAssertion.isEmpty()) {
            try {
                JsonNode assertionResultNode = objectMapper.readTree(caseapiAssertion);
                return assertResponse(assertionResultNode, response, statusCode, responseHeaders, execLog, variables);
            } catch (Exception e) {
                execLog.append(formatLog("Error", "断言解析异常: " + e.getMessage()));
                return false;
            }
        }
        return true;
    }

    //API用例结果保存逻辑
    private void saveApiCaseResult(ApiCaseDTO apiCaseDTO, String reportCollectionCaseId, StringBuilder execLog, long apiDuring, boolean assertionResult, String finalUrl, String processedHeader, String processedBody, Map<String, String> responseHeaders, String response, int statusCode) {
        int caseApiIndex = apiCaseDTO.getIndex() != null ? apiCaseDTO.getIndex() : 0; // 假设默认值为 0
        String apiId = apiCaseDTO.getApiId();
        String apiName = apiMapper.getApiDetail(apiId).getName();
        String caseApiName = apiCaseDTO.getCaseapiName();

        execLog.append(formatLog("Debug", "[" + apiName + "]接口执行开始"));
        execLog.append(formatLog("Debug", "【请求信息】:"));
        execLog.append(formatLog("Debug", apiCaseDTO.getMethod() + " " + finalUrl));
        execLog.append(formatLog("Debug", "请求头: " + processedHeader));
        execLog.append(formatLog("Debug", "请求体: " + processedBody));
        execLog.append(formatLog("Debug", "【响应信息】:"));
        execLog.append(formatLog("Debug", "响应码: " + statusCode));
        execLog.append(formatLog("Debug", "响应头: " + responseHeaders));
        execLog.append(formatLog("Debug", "响应体: " + response));
        execLog.append(formatLog("Debug", "[" + apiName + "]接口执行结束"));

        ReportCollectionCaseApi reportCollectionCaseApi = new ReportCollectionCaseApi();
        String reportCollectionCaseApiId = UUID.randomUUID().toString();
        reportCollectionCaseApi.setId(reportCollectionCaseApiId);
        reportCollectionCaseApi.setReportCollectionCaseId(reportCollectionCaseId);
        reportCollectionCaseApi.setCaseApiIndex(caseApiIndex);
        reportCollectionCaseApi.setApiId(apiId);
        reportCollectionCaseApi.setApiName(apiName);
        reportCollectionCaseApi.setApiPath(finalUrl);
        reportCollectionCaseApi.setExecLog(removeNullCharacters(String.valueOf(execLog)));
        reportCollectionCaseApi.setDuring((int) apiDuring);
        reportCollectionCaseApi.setStatus(String.valueOf(assertionResult));
        reportCollectionCaseApi.setDescription(caseApiName);
        reportCollectionCaseApiMapper.addReportCollectionCaseApi(reportCollectionCaseApi);
    }
    public String runPlan(RunRequest runRequest,String reportId){
        // 1. 初始化环境变量
        // 从请求中获取环境变量，并将其存储到全局变量集合中
        Map<String, String> variables = initializeEnvironmentVariables(runRequest);
        // 2. 初始化测试报告
        initializeReport(runRequest, reportId);
        // 3.获取测试计划相关信息
        String planId = runRequest.getSourceId();
        String planName = runRequest.getSourceName();
        List<PlanCollectionDTO> planCollectionDTOS=planCollectionMapper.getPlanCollectionList(planId);
        int collectionTotal=planCollectionDTOS.size();
        //4.遍历每个集合并执行
        for (int i = 0; i < planCollectionDTOS.size(); i++) {
            String collectionId= planCollectionDTOS.get(i).getCollectionId();
            CollectionDTO collectionDTO=collectionMapper.getCollectionDetail(collectionId);
            String collectionName=collectionDTO.getName();
            //5.获取集合中的用例列表
            List<String> collectionCaseDTOList = collectionCaseMapper.getCaseIdList(collectionId);
            int caseTotal = collectionCaseDTOList.size();
            // 6. 初始化集合报告
            // 生成唯一的集合报告ID，并插入集合报告记录到数据库
            String reportCollectionId = initializeReportCollection(reportId, collectionId, collectionName, caseTotal);
            // 7. 遍历集合中的用例并执行
            // 对集合中的每个用例，执行测试逻辑
            for (String caseId : collectionCaseDTOList) {
                executeCase(caseId, collectionId, reportCollectionId, variables);
            }
        }
        //8. 插入report_statistics
        insertReportStatisticsPlan(reportId, collectionTotal);
        // 9. 更新报告状态和结束时间
        // 将报告状态更新为“成功”，并记录报告的结束时间
        reportMapper.updateReportStatus("success", reportId);
        reportMapper.updateReportEndTime(reportId, System.currentTimeMillis(), System.currentTimeMillis());
        // 10.返回成功
        return reportId;

    }

    //重构后的run方法
    public String run(RunRequest runRequest,String reportId) {
        // 1. 初始化环境变量
        // 从请求中获取环境变量，并将其存储到全局变量集合中
        Map<String, String> variables = initializeEnvironmentVariables(runRequest);
        // 2. 初始化测试报告
        initializeReport(runRequest, reportId);
        // 3. 获取集合信息
        // 从请求中获取集合ID和集合名称，并查询集合中包含的用例列表
        String collectionId = runRequest.getSourceId();
        String collectionName = runRequest.getSourceName();
        List<String> collectionCaseDTOList = collectionCaseMapper.getCaseIdList(collectionId);
        int caseTotal = collectionCaseDTOList.size();
        // 4. 初始化集合报告
        // 生成唯一的集合报告ID，并插入集合报告记录到数据库
        String reportCollectionId = initializeReportCollection(reportId, collectionId, collectionName, caseTotal);
        // 5. 遍历集合中的用例并执行
        // 对集合中的每个用例，执行测试逻辑
        for (String caseId : collectionCaseDTOList) {
            executeCase(caseId, collectionId, reportCollectionId, variables);
        }
        // 6. 更新报告状态和结束时间
        // 将报告状态更新为“成功”，并记录报告的结束时间
        reportMapper.updateReportStatus("success", reportId);
        reportMapper.updateReportEndTime(reportId, System.currentTimeMillis(), System.currentTimeMillis());
        // 7. 插入report_statistics
        insertReportStatistics(reportId, reportCollectionId, caseTotal);
        // 8.返回成功
        return reportId;
    }

    // 单独提取的方法：插入report_statistics
    private void insertReportStatistics(String reportId, String reportCollectionId, int caseTotal) {
        ReportStatisticsDTO reportStatisticsDto = new ReportStatisticsDTO();
        reportStatisticsDto.setId(UUID.randomUUID().toString());
        reportStatisticsDto.setReportId(reportId);
        reportStatisticsDto.setTotal(caseTotal);
        reportStatisticsDto.setPassCount(reportCollectionCaseMapper.countReportCollectionResultTrue(reportCollectionId));
        reportStatisticsDto.setFailCount(reportCollectionCaseMapper.countReportCollectionResultFalse(reportCollectionId));
        reportStatisticsDto.setErrorCount(0);
        reportStatisticsMapper.addReportStatistics(reportStatisticsDto);
    }
    private void insertReportStatisticsPlan(String reportId,int caseTotal){
        ReportStatisticsDTO reportStatisticsDto = new ReportStatisticsDTO();
        reportStatisticsDto.setId(UUID.randomUUID().toString());
        reportStatisticsDto.setReportId(reportId);
        reportStatisticsDto.setTotal(caseTotal);
        reportStatisticsDto.setPassCount(reportCollectionMapper.countReportCollectionResultTrue(reportId));
        reportStatisticsDto.setFailCount(reportCollectionMapper.countReportCollectionResultFalse(reportId));
        reportStatisticsDto.setErrorCount(0);
        reportStatisticsMapper.addReportStatistics(reportStatisticsDto);
    }



    private JsonNode parseController(String controllerJson) {
        if (controllerJson == null || controllerJson.isEmpty()) {
            return null;
        }
        try {
            return objectMapper.readTree(controllerJson);
        } catch (JsonProcessingException e) {
            logger.error("解析 controllerJson 失败: " + e.getMessage());
            return null;
        }
    }

    private String extractScript(JsonNode controllerNode, String scriptName) {
        if (controllerNode == null || !controllerNode.isArray()) {
            return null;
        }
        for (JsonNode scriptNode : controllerNode) {
            String name = scriptNode.get("name").asText();
            String value = scriptNode.get("value").asText();
            if (scriptName.equals(name)) {
                return value;
            }
        }
        return null;
    }

    private boolean executePreScript(String preScript, Map<String, String> variables, StringBuilder execLog) {
        if (preScript == null || preScript.isEmpty()) {
            return true;
        }
        try {
            // 执行前置脚本
            GraalVMScriptUtils.eval(preScript, variables);
            // 获取脚本执行后的变量
            Map<String, Object> scriptVariables = GraalVMScriptUtils.getScriptVariables();
            for (Map.Entry<String, Object> entry : scriptVariables.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                logger.info("前置脚本: key值为" + key + ", value值为" + value);
                execLog.append(formatLog("Debug", "前置脚本: key值为" + key + ", value值为" + value));
                if (value != null) {
                    variables.put(key, value.toString());
                }
            }
            return true; // 执行成功
        } catch (Exception e) {
            logger.error("前置脚本执行失败: " + e.getMessage());
            execLog.append(formatLog("Error", "前置脚本执行失败: " + e.getMessage()));
            return false; // 执行失败
        }
    }

    private JsonNode parseJson(String jsonString) {
        if (jsonString == null || jsonString.isEmpty()) {
            return null;
        }
        try {
            return objectMapper.readTree(jsonString);
        } catch (JsonProcessingException e) {
            logger.error("解析 JSON 失败: " + e.getMessage());
            return null;
        }
    }

    private String processJsonNode(JsonNode jsonNode, Map<String, String> variables) {
        if (jsonNode == null) {
            return null;
        }
        String jsonString = jsonNode.toString();
        return processVariableUtils.processStr(jsonString, variables);
    }

    private boolean executePostScript(String postScript, Map<String, String> variables, StringBuilder execLog) {
        if (postScript == null || postScript.isEmpty()) {
            return true; // 如果没有脚本，直接返回成功
        }

        try {
            // 执行后置脚本
            GraalVMScriptUtils.eval(postScript, variables);
            // 获取脚本执行后的变量
            Map<String, Object> scriptVariables = GraalVMScriptUtils.getScriptVariables();
            for (Map.Entry<String, Object> entry : scriptVariables.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                logger.info("后置脚本: key值为" + key + ", value值为" + value);
                execLog.append(formatLog("Debug", "后置脚本: key值为" + key + ", value值为" + value));
                if (value != null) {
                    variables.put(key, value.toString());
                }
            }
            return true; // 执行成功
        } catch (Exception e) {
            logger.error("后置脚本执行失败: " + e.getMessage());
            execLog.append(formatLog("Error", "后置脚本执行失败: " + e.getMessage()));
            return false; // 执行失败
        }
    }

    private String removeNullCharacters(String input) {
        if (input == null) {
            return null;
        }
        return input.replaceAll("\u0000", ""); // 移除所有空字符
    }

    public String debugRun(RunRequest runRequest){
        // 1. 初始化环境变量
        Map<String, String> variables = initializeEnvironmentVariables(runRequest);

        // 2. 获取单个接口用例的详细信息
        String apiCaseId = runRequest.getSourceId(); // 直接获取接口用例的 ID
        ApiCaseDTO apiCaseDTO = caseApiMapper.getCaseApiDetailByCaseApiId(apiCaseId); // 根据 ID 获取 ApiCaseDTO
        if (apiCaseDTO == null) {
            return formatLog("Error", "未找到接口用例: " + apiCaseId);
        }

        // 4. 执行单个接口用例
        String reportCollectionCaseId = "debug-" + UUID.randomUUID().toString();
        executeApiCase(apiCaseDTO, reportCollectionCaseId, variables);

        // 5. 返回执行日志
        return reportCollectionCaseId;
    }


    public String debugRunCase(RunRequest runRequest){
        // 1. 初始化环境变量
        Map<String, String> variables = initializeEnvironmentVariables(runRequest);
        // 2. 获取单个用例的详细信息
        String caseId = runRequest.getSourceId(); // 获取用例的 ID
        String caseName = caseMapper.getCaseName(caseId); // 根据 ID 获取用例名称
        if (caseName == null) {
            return formatLog("Error", "未找到用例: " + caseId);
        }
        //3. 生成唯一的集合报告 ID
        String reportCollectionId = "debug-" + UUID.randomUUID().toString();

        //4. 执行单个用例
        executeCase(caseId, "debug-collection", reportCollectionId, variables);

        //5. 返回reportCollectionId
        return reportCollectionId;
    }

    @Async("taskExecutor")
    public void runAsync(RunRequest runRequest,String reportId) {

        long currentTime = System.currentTimeMillis();
        ReportStatus reportStatus=new ReportStatus();
        reportStatus.setReportId(reportId);
        reportStatus.setStatus("pending");
        reportStatus.setStartTime(currentTime);
        reportStatusMapper.add(reportStatus);

        try {
            // 执行任务
            run(runRequest,reportId);
            // 任务完成后，落入数据库表
            reportStatus.setStatus("success");
            reportStatus.setEndTime(System.currentTimeMillis());
            reportStatusMapper.update(reportStatus);

            // 发送成功邮件
            String collectionId = runRequest.getSourceId();
            CollectionDTO collectionDTO=collectionMapper.getCollectionDetail(collectionId);
            String  emailField=collectionDTO.getEmail();
            // 使用逗号分隔字符串
            String[] emails = emailField.split(",");
            // 打印分隔后的结果
            for (String email : emails) {
                logger.info("发送邮件参数"+email+",发件人");
                // 2. 发送纯文本邮件
                EmailUtils.sendTextEmail(
                        "",
                        email,
                        "自动化测试报告",
                        "报告"+reportId
                );
            }
        } catch (Exception e) {
            // 捕获异常并返回错误信息
            logger.error("异步任务执行失败: " + e.getMessage(), e);
            reportStatus.setStatus("fail");
            reportStatus.setEndTime(System.currentTimeMillis());
            reportStatusMapper.update(reportStatus);
            // 发送失败邮件
            String collectionId = runRequest.getSourceId();
            CollectionDTO collectionDTO=collectionMapper.getCollectionDetail(collectionId);
            String  emailField=collectionDTO.getEmail();
            // 使用逗号分隔字符串
            String[] emails = emailField.split(",");
            // 打印分隔后的结果
            for (String email : emails) {
                // 2. 发送纯文本邮件
                try {
                    EmailUtils.sendTextEmail(
                            "",
                            email,
                            "自动化测试报告",
                            "执行失败，报告"+reportId
                    );
                } catch (MessagingException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }

    public String getReportStatus(String reportId){
        return reportStatusMapper.getStatus(reportId);
    }

    /**
     * 数据库相关操作--开始
     */
    public boolean executeSqlScript(String environmentId, String sqlValue, Map<String, String> variables, StringBuilder execLog) {
        if (sqlValue == null || sqlValue.isEmpty()) {
            return true; // 如果没有 SQL 脚本，直接返回成功
        }

        try {
            // 解析 SQL value
            JsonNode sqlNode = parseSqlValue(sqlValue);
            if (sqlNode == null) {
                return false;
            }

            String dbKey = sqlNode.get("db").asText();
            String sqlType = sqlNode.get("sqlType").asText();
            String names = sqlNode.has("names") ? sqlNode.get("names").asText() : null;
            String sqlText = sqlNode.get("sqlText").asText();

            // 获取数据库连接信息
            Map<String, String> dbConnectionInfo = getDatabaseConnectionInfo(environmentId, dbKey);
            if (dbConnectionInfo == null) {
                execLog.append(formatLog("Error", "未找到数据库连接信息: dbKey=" + dbKey));
                return false;
            }

            // 处理 SQL 文本中的变量
            sqlText = processVariableUtils.processStr(sqlText, variables);

            // 执行 SQL
            if ("query".equalsIgnoreCase(sqlType)) {
                // 查询语句
                List<Map<String, Object>> result = executeQuery(
                        dbConnectionInfo.get("url"),
                        dbConnectionInfo.get("user"),
                        dbConnectionInfo.get("password"),
                        sqlText
                );

                if (result != null && !result.isEmpty()) {
                    // 处理查询结果
                    // 处理查询结果
                    Map<String, String> nameMap = new HashMap<>();
                    if (names != null && !names.isEmpty()) {
                        String[] nameArray = names.split(",");
                        for (String name : nameArray) {
                            nameMap.put(name.trim(), null); // 初始化为 null
                        }
                    }

                    Map<String, Object> firstRow = result.get(0);
                    for (String name : nameMap.keySet()) {
                        Object value = firstRow.get(name.toLowerCase());
                        if (value != null) {
                            variables.put(name, value.toString());
                            execLog.append(formatLog("Debug", "SQL 查询结果: key=" + name + ", value=" + value));
                        }
                    }
                }
            } else if ("nonQuery".equalsIgnoreCase(sqlType)) {
                // 非查询语句
                int affectedRows =executeNonQuery(
                        dbConnectionInfo.get("url"),
                        dbConnectionInfo.get("port"),
                        dbConnectionInfo.get("user"),
                        dbConnectionInfo.get("password"),
                        sqlText
                );
                execLog.append(formatLog("Debug", "SQL 执行成功: affectedRows=" + affectedRows));
            } else {
                execLog.append(formatLog("Error", "不支持的 SQL 类型: " + sqlType));
                return false;
            }

            return true; // 执行成功
        } catch (Exception e) {
            logger.error("SQL 脚本执行失败: " + e.getMessage());
            execLog.append(formatLog("Error", "SQL 脚本执行失败: " + e.getMessage()));
            return false; // 执行失败
        }
    }
    public Map<String, String> getDatabaseConnectionInfo(String environmentId, String dbKey) {
        Database database = databaseMapper.getDatabaseByName(environmentId,dbKey);
        if (database == null) {
            throw new RuntimeException("未找到数据库配置: environmentId=" + environmentId + ", dbKey=" + dbKey);
        }

        // 解析 connectInfo
        Map<String, String> connectInfo = parseConnectInfo(database.getConnectInfo());

        // 生成数据库连接 URL
        String url = buildDatabaseUrl(database.getDatabaseType(), connectInfo);

        // 返回连接信息
        Map<String, String> result = new HashMap<>();
        result.put("url", url);
        result.put("user", connectInfo.get("user"));
        result.put("password", connectInfo.get("password"));
        return result;
    }
    private static Map<String, String> parseConnectInfo(String connectInfo) {
        try {
            JsonNode node = objectMapper.readTree(connectInfo);
            Map<String, String> result = new HashMap<>();
            result.put("host", node.get("host").asText());
            result.put("port", node.get("port").asText());
            result.put("user", node.get("user").asText());
            result.put("password", node.get("password").asText());
            result.put("databaseName", node.get("databaseName").asText());
            return result;
        } catch (Exception e) {
            throw new RuntimeException("解析 connectInfo 失败: " + e.getMessage());
        }
    }
    private static String buildDatabaseUrl(String databaseType, Map<String, String> connectInfo) {
        String host = connectInfo.get("host");
        String port = connectInfo.get("port");
        String database = connectInfo.get("databaseName");

        switch (databaseType.toLowerCase()) {
            case "mysql":
                return String.format("jdbc:mysql://%s:%s/%s", host, port, database);
            case "pgsql":
                return String.format("jdbc:postgresql://%s:%s/%s", host, port, database);
            case "oracle":
                // 假设使用 SID
                return String.format("jdbc:oracle:thin:@%s:%s:%s", host, port, database);
            case "mssql":
                return String.format("jdbc:sqlserver://%s:%s;databaseName=%s", host, port, database);
            default:
                throw new IllegalArgumentException("不支持的数据库类型: " + databaseType);
        }
    }

    public static JsonNode parseSqlValue(String sqlValue) {
        if (sqlValue == null || sqlValue.isEmpty()) {
            return null;
        }
        try {
            return objectMapper.readTree(sqlValue);
        } catch (Exception e) {
            logger.error("解析 SQL value 失败: " + e.getMessage());
            return null;
        }
    }
    public static List<Map<String, Object>> executeQuery(String url, String user, String password, String sqlText) {
        List<Map<String, Object>> result = new ArrayList<>();
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            // 建立数据库连接
            connection = DriverManager.getConnection(url, user, password);

            // 创建 Statement 并执行查询
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sqlText);

            // 处理查询结果
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();

            while (resultSet.next()) {
                Map<String, Object> row = new HashMap<>();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    Object columnValue = resultSet.getObject(i);
                    row.put(columnName, columnValue);
                }
                result.add(row);
            }
        } catch (SQLException e) {
            throw new RuntimeException("执行 SQL 查询失败: " + e.getMessage());
        } finally {
            // 关闭资源
            closeResources(connection, statement, resultSet);
        }

        return result;
    }
    /**
     * 关闭数据库资源
     *
     * @param connection 数据库连接
     * @param statement  Statement 对象
     * @param resultSet  ResultSet 对象
     */
    private static void closeResources(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /**
     * 执行非查询 SQL（如 INSERT、UPDATE、DELETE）
     * @param host     数据库主机地址
     * @param port     数据库端口
     * @param user     数据库用户名
     * @param password 数据库密码
     * @param sqlText  SQL 语句
     * @return 受影响的行数
     */
    public static int executeNonQuery(String host, String port, String user, String password, String sqlText) {
        Connection connection = null;
        Statement statement = null;

        try {
            // 建立数据库连接
            String url = "jdbc:mysql://" + host + ":" + port + "/your_database_name"; // 替换为实际的数据库名称
            connection = DriverManager.getConnection(url, user, password);

            // 创建 Statement 并执行 SQL
            statement = connection.createStatement();
            return statement.executeUpdate(sqlText);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("执行 SQL 失败: " + e.getMessage());
        } finally {
            // 关闭资源
            closeResources(connection, statement, null);
        }
    }



    /**
    * 数据库相关操作--结束
    */


}
